/**
 * 数据预览表格组件
 * 提供数据表格的展示和分页功能
 */
class PreviewTable {
    constructor(containerId, options = {}) {
        this.containerId = containerId;
        this.container = document.getElementById(containerId);
        this.options = {
            pageSize: options.pageSize || 20,
            showPagination: options.showPagination !== false,
            showStats: options.showStats !== false,
            sortable: options.sortable !== false,
            ...options
        };
        
        this.data = [];
        this.columns = [];
        this.totalRecords = 0;
        this.currentPage = 1;
        this.executionTime = 0;
        
        this.init();
    }

    /**
     * 初始化组件
     */
    init() {
        if (!this.container) {
            console.error(`容器元素 ${this.containerId} 不存在`);
            return;
        }
        
        this.render();
    }

    /**
     * 加载数据
     */
    loadData(data, columns = [], totalRecords = 0, executionTime = 0) {
        this.data = data || [];
        this.columns = columns.length > 0 ? columns : (this.data.length > 0 ? Object.keys(this.data[0]) : []);
        this.totalRecords = totalRecords || this.data.length;
        this.executionTime = executionTime || 0;
        this.currentPage = 1;
        
        this.render();
    }

    /**
     * 渲染组件
     */
    render() {
        const html = this.generateHtml();
        this.container.innerHTML = html;
        
        // 绑定事件
        this.bindEvents();
    }

    /**
     * 生成HTML
     */
    generateHtml() {
        let html = '<div class="preview-table-container">';
        
        // 统计信息
        if (this.options.showStats) {
            html += this.generateStatsHtml();
        }
        
        // 表格
        html += this.generateTableHtml();
        
        // 分页
        if (this.options.showPagination && this.totalRecords > this.options.pageSize) {
            html += this.generatePaginationHtml();
        }
        
        html += '</div>';
        
        return html;
    }

    /**
     * 生成统计信息HTML
     */
    generateStatsHtml() {
        const totalPages = Math.ceil(this.totalRecords / this.options.pageSize);
        
        return `
            <div class="table-stats mb-4 p-3 bg-gray-50 rounded-lg">
                <div class="flex justify-between items-center text-sm text-gray-600">
                    <div class="flex space-x-4">
                        <span>总记录数: <strong>${this.totalRecords.toLocaleString()}</strong></span>
                        <span>当前页: <strong>${this.currentPage}/${totalPages}</strong></span>
                        <span>执行时间: <strong>${this.executionTime}ms</strong></span>
                    </div>
                    <div class="flex items-center space-x-2">
                        <label class="text-sm">每页显示:</label>
                        <select class="page-size-select border rounded px-2 py-1 text-sm" onchange="previewTable.changePageSize(this.value)">
                            <option value="10" ${this.options.pageSize === 10 ? 'selected' : ''}>10</option>
                            <option value="20" ${this.options.pageSize === 20 ? 'selected' : ''}>20</option>
                            <option value="50" ${this.options.pageSize === 50 ? 'selected' : ''}>50</option>
                            <option value="100" ${this.options.pageSize === 100 ? 'selected' : ''}>100</option>
                        </select>
                    </div>
                </div>
            </div>
        `;
    }

    /**
     * 生成表格HTML
     */
    generateTableHtml() {
        if (this.data.length === 0) {
            return `
                <div class="empty-state text-center py-8">
                    <i class="fas fa-inbox text-gray-400 text-4xl mb-4"></i>
                    <p class="text-gray-500">暂无数据</p>
                </div>
            `;
        }

        const startIndex = (this.currentPage - 1) * this.options.pageSize;
        const endIndex = Math.min(startIndex + this.options.pageSize, this.data.length);
        const pageData = this.data.slice(startIndex, endIndex);

        let html = `
            <div class="table-wrapper overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
        `;

        // 表头
        this.columns.forEach((column, index) => {
            const sortIcon = this.options.sortable ? 
                '<i class="fas fa-sort ml-1 text-gray-400"></i>' : '';
            html += `
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    ${column}
                    ${sortIcon}
                </th>
            `;
        });

        html += `
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
        `;

        // 表格数据
        pageData.forEach((row, rowIndex) => {
            html += '<tr>';
            this.columns.forEach(column => {
                const cellValue = this.formatCellValue(row[column]);
                html += `
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                        ${cellValue}
                    </td>
                `;
            });
            html += '</tr>';
        });

        html += `
                    </tbody>
                </table>
            </div>
        `;

        return html;
    }

    /**
     * 生成分页HTML
     */
    generatePaginationHtml() {
        const totalPages = Math.ceil(this.totalRecords / this.options.pageSize);
        const startPage = Math.max(1, this.currentPage - 2);
        const endPage = Math.min(totalPages, this.currentPage + 2);

        let html = `
            <div class="pagination-wrapper flex justify-center items-center space-x-2 mt-4">
                <button 
                    class="pagination-btn px-3 py-1 text-sm border rounded ${this.currentPage === 1 ? 'bg-gray-100 text-gray-400 cursor-not-allowed' : 'bg-white text-gray-700 hover:bg-gray-50'}"
                    onclick="previewTable.goToPage(${this.currentPage - 1})"
                    ${this.currentPage === 1 ? 'disabled' : ''}
                >
                    <i class="fas fa-chevron-left"></i>
                </button>
        `;

        // 页码按钮
        for (let i = startPage; i <= endPage; i++) {
            const isActive = i === this.currentPage;
            html += `
                <button 
                    class="pagination-btn px-3 py-1 text-sm border rounded ${isActive ? 'bg-blue-500 text-white' : 'bg-white text-gray-700 hover:bg-gray-50'}"
                    onclick="previewTable.goToPage(${i})"
                >
                    ${i}
                </button>
            `;
        }

        html += `
                <button 
                    class="pagination-btn px-3 py-1 text-sm border rounded ${this.currentPage === totalPages ? 'bg-gray-100 text-gray-400 cursor-not-allowed' : 'bg-white text-gray-700 hover:bg-gray-50'}"
                    onclick="previewTable.goToPage(${this.currentPage + 1})"
                    ${this.currentPage === totalPages ? 'disabled' : ''}
                >
                    <i class="fas fa-chevron-right"></i>
                </button>
            </div>
        `;

        return html;
    }

    /**
     * 格式化单元格值
     */
    formatCellValue(value) {
        if (value === null || value === undefined) {
            return '-';
        }
        
        if (typeof value === 'boolean') {
            return value ? '是' : '否';
        }
        
        if (typeof value === 'number') {
            return value.toLocaleString();
        }
        
        if (typeof value === 'string') {
            // 截断过长的字符串
            return value.length > 100 ? value.substring(0, 100) + '...' : value;
        }
        
        return String(value);
    }

    /**
     * 绑定事件
     */
    bindEvents() {
        // 这里可以添加排序等事件处理
        if (this.options.sortable) {
            const headers = this.container.querySelectorAll('th');
            headers.forEach((header, index) => {
                header.style.cursor = 'pointer';
                header.addEventListener('click', () => {
                    this.sortByColumn(index);
                });
            });
        }
    }

    /**
     * 跳转到指定页
     */
    goToPage(page) {
        const totalPages = Math.ceil(this.totalRecords / this.options.pageSize);
        if (page >= 1 && page <= totalPages) {
            this.currentPage = page;
            this.render();
            
            // 触发分页变化事件
            this.dispatchEvent('pageChange', {
                page: this.currentPage,
                pageSize: this.options.pageSize
            });
        }
    }

    /**
     * 改变每页显示数量
     */
    changePageSize(pageSize) {
        this.options.pageSize = parseInt(pageSize);
        this.currentPage = 1;
        this.render();
        
        // 触发分页变化事件
        this.dispatchEvent('pageChange', {
            page: this.currentPage,
            pageSize: this.options.pageSize
        });
    }

    /**
     * 按列排序
     */
    sortByColumn(columnIndex) {
        const column = this.columns[columnIndex];
        // 这里可以实现排序逻辑
        console.log(`按列 ${column} 排序`);
    }

    /**
     * 分发事件
     */
    dispatchEvent(eventName, detail) {
        const event = new CustomEvent(eventName, { detail });
        this.container.dispatchEvent(event);
    }

    /**
     * 刷新数据
     */
    refresh() {
        this.render();
    }

    /**
     * 销毁组件
     */
    destroy() {
        if (this.container) {
            this.container.innerHTML = '';
        }
    }
}

// 导出为全局变量
window.PreviewTable = PreviewTable;